package com.hfzy.ihk.common.support.redis;

import com.hfzy.ihk.common.util.string.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2016/6/23.
 * 使用redis来生成唯一id
 * @author wws
 */
@Component
@ConditionalOnProperty(prefix = "spring.redis.customConfig",name = "enable")
public class IdGenerator {

    private static int reTry = 1; //重试次数

    static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        IdGenerator.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 产生ID
     * @param tableName key值
     * @
     * */
    public static Long generate(String tableName){

        if(StringUtil.isEmpty(tableName)) {
            throw new RuntimeException("tableName can't null");
        }

        int tryTime = 0;

        Long seq = stringRedisTemplate.opsForValue().increment(tableName,1L);

        while ((seq == 0) && (tryTime < reTry)){
            tryTime++;
            System.out.println("Redis Id generator ERROR->try time:"+tryTime);
            seq =stringRedisTemplate.opsForValue().increment(tableName,1L);
        }

        if(seq == 0){
            throw new RuntimeException("id generate failure!");
        }

        return seq;
    }
}
